package com.test;

import java.net.Socket;
import java.util.List;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;

class SocketPreview extends Thread{
	private static final String TAG = "Preview";

	private Camera camera;
	private PreviewCallbacker callbacker;

	SocketPreview(AndroidSocketConnect context, Socket socket) {

		Log.v(TAG, "AndroidSocketConnect camera.open");
		camera = Camera.open();

		//set parameters for decoding later
		Log.v(TAG, "AndroidSocketConnect setting params");
		Camera.Parameters params = camera.getParameters();

		List<Size> sizes = params.getSupportedPreviewSizes();
		for (Size size : sizes){
			Log.v(TAG, size.width+" by "+size.height);
		}
		Size size = sizes.get(sizes.size()-1);

		Log.v(TAG, "AndroidSocketConnect set preview size: "+size.width+" by "+size.height);
		params.setPreviewSize(size.width, size.height);

		Log.v(TAG, "AndroidSocketConnect set preview format: ImageFormat.NV21-"+ImageFormat.NV21);
		params.setPreviewFormat(ImageFormat.NV21);

		Log.v(TAG, "AndroidSocketConnect supported framerates:");
		List<Integer> framerates = params.getSupportedPreviewFrameRates();
		for (Integer framerate : framerates){
			Log.v(TAG, framerate.toString());
		}
		Log.v(TAG, "AndroidSocketConnect set framerate: "+15);
		params.setPreviewFrameRate(15);

		camera.setParameters(params);

		//create a pool of byte buffers to be added to the camera.
		//frames have been tested as having length of 38016
		//this is found by "width, height, and bytes per pixel"
		//The width and height can be read from getPreviewSize(). 
		//Bytes per pixel can be computed from getBitsPerPixel(int) / 8, 
		//using the image format from getPreviewFormat()
		//camera.addCallbackBuffer(new byte[38016]);
		//camera.addCallbackBuffer(new byte[38016]);
		//camera.addCallbackBuffer(new byte[38016]);
		//camera.addCallbackBuffer(new byte[38016]);
		//camera.addCallbackBuffer(new byte[38016]);

		callbacker = new PreviewCallbacker(socket, context);
		camera.setPreviewCallback(callbacker);

		camera.startPreview();
	}

	public synchronized void close(){
		try{
			if(camera != null){
				camera.stopPreview();
				camera.setPreviewCallback(null);
				camera.release();
				camera = null;

				callbacker.close();
				callbacker = null;

			}
		}
		catch(RuntimeException e){
			Log.v(TAG, "AndroidSocketConnect runtime exception");
		}
	}
}